// MINI UI解析
mini.parse();

/**
 * 订单商品信息处理器类
 */
function OrderGoodsHandler() {

}

// 实例化全局订单处理器
OrderGoodsHandler.instance = new OrderGoodsHandler();
OrderGoodsHandler.mgrData = new OrderMgrData();
OrderGoodsHandler.orderGoodsGrid = mini.get("orderGoodsGrid");
OrderGoodsHandler.hiddenForm = new mini.Form("hiddenForm");
OrderGoodsHandler.hiddenForm.loadingMsg = OrderGoodsHandler.mgrData.loadingMsg;

// 获得订单流程处理控件对象
OrderGoodsHandler.queRBtn = mini.get("queRBtn");

// 商品品牌默认选项
OrderGoodsHandler.goodsComboxData = {};

/**
 * 加载订单商品列表
 */
OrderGoodsHandler.loadOrderGoods = function() {
	OrderGoodsHandler.orderGoodsGrid.url = OrderGoodsHandler.mgrData
			.loadOrderGoodsUrl(__boiId);
	OrderGoodsHandler.orderGoodsGrid.load();
}

/**
 * 初始化数据
 */
OrderGoodsHandler.init = function() {
	OrderGoodsHandler.loadOrderGoods();
};

OrderGoodsHandler.init();

/**
 * 返回按钮点击事件处理程序
 */
OrderGoodsHandler.returnOrderDetail = function() {
	window.location.href = "orderDetail.jsp?boiId=" + __boiId + "&bmbId=" + __bmbId;
}

OrderGoodsHandler.removeOrderGoods = function() {
	var rowData = OrderGoodsHandler.orderGoodsGrid.getSelected();
	OrderGoodsHandler.orderGoodsGrid.removeRow(rowData);
}

/**
 * 表格绘画事件处理程序
 */
OrderGoodsHandler.orderGoodsGrid.on("drawcell", function(e) {
	var record = e.record;
	var value = e.value;
	var html = "";

	if (e.field == "bogPrice") {
		html = "0.00";
		if (value != "") html = parseFloat(value).toFixed(2);
	} else if (e.field == "bogAttprice") {
		html = "0.00";
		if (value != "") html = parseFloat(value).toFixed(2);
	} else if (e.field == "bogTotal") {
		if (record.bogNumber != "") {
			var bogPrice = parseFloat(record.bogPrice);
			var bogAttprice = parseFloat(record.bogAttprice);
			var total = bogPrice + bogAttprice;
			var num = record.bogNumber;
			html = parseFloat(total * num).toFixed(2);
			record.bogTotal = html;
		}
	} else if (e.field == "boiOperate") {
		html = "<span><a style='cursor: pointer;' onclick='OrderGoodsHandler.removeOrderGoods()'>移除</a></span>";
	}

	if (html) e.cellHtml = html;

});

/**
 * 单元额汇总处理程序
 * 
 * @param {}
 *            e
 */
OrderGoodsHandler.orderGoodsGrid.on("drawsummarycell", function(e) {
	var result = e.result;
	var grid = e.sender;
	var rows = e.data;

	if (e.field == "bogTotal") {
		var total = 0;
		for (var i = 0, l = rows.length; i < l; i++) {
			var row = rows[i];
			var xiaoJi = (parseFloat(record.bogPrice) + parseFloat(record.bogAttprice))
					* parseFloat(record.bogNumber);
			if (isNaN(xiaoJi))
				continue;
			total += xiaoJi;
		}

		e.cellHtml = "总计: " + total;
	}
});

/**
 * 提交单元格编辑数据前触发
 */
OrderGoodsHandler.orderGoodsGrid.on("cellcommitedit", function(e) {
	e.editor.validate();
	
	if (!e.editor.isValid())
		e.cancel = true;
});

/**
 * 搜索商品按钮点击事件处理程序
 */
OrderGoodsHandler.searchGoods = function() {
	var searchGoodsInput = mini.get("searchGoodsInput");
	if (!searchGoodsInput.validate())
		return;
	var value = searchGoodsInput.getValue();

	$.ajax({
				url : __root + "/getGoodsCombobox.do",
				type : "POST",
				cache : false,
				data : {
					value : value
				},
				dataType : 'json',
				success : function(text) {
					if (text.length > 0) {
						var temp = [OrderGoodsHandler.goodsComboxData];
						
						for (var i = 0; i < text.length; i++) {
							var item = {
								id : text[i].bgiId,
								text : text[i].bgiName
							};
							temp[i] = item;
						}
						
						mini.get("goodsName").setData(temp);
						mini.get("goodsName").setValue(temp[0].id);
						OrderGoodsHandler.getGoodsInfoById(temp[0].id);
					} else {
						mini.get("goodsName").setData(null);
						mini.get("goodsNum").hide();
						$("#goodsInfoTable").find(".clear").text("");
					}
				},
				error : function(jqXHR, textStatus, errorThrown) {
					MiniuiTools.miniError("系统提示", jqXHR.responseText);
				}
			});
}

/**
 * 加载指定商品对应的信息
 * @param {} id
 */
OrderGoodsHandler.getGoodsInfoById = function(id) {
	$.ajax({
		url : __root + "/showGoodsInfoById.do",
		type : "POST",
		cache : false,
		data : {
			bgiId : id
		},
		success : function(text) {
			mini.get("goodsNum").show();
			$("#goodsInfoTable").find(".clear").text("");
			$("#bgiName").append('<label id="' + text[0].bgiId + '">'
					+ text[0].bgiName + '</label>');
			$("#bgiGsn").append('<label>' + text[0].bgiGsn + '</label>');
			$("#bgiGroup").append(text[0].bggName);
			$("#bgiBrand").append(text[0].bgbName);
			$("#bgiPrice")
					.append('<input id="rgShop" type="radio" name="rgPrice" checked="checked" value="'
							+ text[0].bgiPrice.toFixed(2)
							+ '" />本店售价['
							+ text[0].bgiPrice.toFixed(2)
							+ ']');
			$("#bgiMarket")
					.append('<input id="rgMarket" type="radio" name="rgPrice" value="'
							+ text[0].bgiMarket.toFixed(2)
							+ '" />市场售价['
							+ text[0].bgiMarket.toFixed(2) + ']');
			$("#bgiCustom")
					.append('<input id="rgCustom" type="radio" name="rgPrice" />自定义：<input id="custom" class="mini-textbox" required="true" style="width:80px;"/>')
			OrderGoodsHandler.getGoodsAttrById(id);
			mini.parse();
		},
		error : function(jqXHR, textStatus, errorThrown) {
			MiniuiTools.miniError("系统提示", jqXHR.responseText);
		}
	});
}

/**
 * 获得商品属性列表
 * @param {} id
 */
OrderGoodsHandler.getGoodsAttrById = function(id) {
	$.ajax({
		url : __root + "/showGoodsAttrById.do",
		type : "POST",
		cache : false,
		data : {
			bgiId : id
		},
		success : function(text) {
			var bgaTattri = "";
			if (text != null) {
				switch (text[0].btaAtype) {
					case 0 :
						$("#goodsAttr").append(text[0].btaName + ": "
								+ text[0].bgaValue);
						break;
					case 1 :
						$("#goodsAttr").append('<span>' + text[0].btaName + '</span>'
								+ ': <input id="rg-0" type="radio" name="rg-'
								+ text[0].bgaTattri + '" value="'
								+ text[0].bgaPrice + '" checked="checked"/><label for="rg-0">'
								+ text[0].bgaValue + '[+' + text[0].bgaPrice.toFixed(2)
								+ ']</label>');
						break;
					case 2 :
						$("#goodsAttr").append('<span>' + text[0].btaName + '</span>'
										+ ': <input id="cb-0" type="checkbox" name="cb-'
										+ text[0].bgaTattri + '" value="'
										+ text[0].bgaPrice
										+ '" /><label for="cb-0">'
										+ text[0].bgaValue + '[+'
										+ text[0].bgaPrice.toFixed(2) + ']</label>');
						break;
					default :
						break;
				}
				
				bgaTattri = text[0].bgaTattri;
				for (var i = 1, j = text.length; i < j; i++) {
					if (text[i].bgaTattri == bgaTattri) {
						// 追加属性
						switch (text[i].btaAtype) {
							case 0 :
								$("#goodsAttr").append(" " + text[i].bgaValue);
								break;
							case 1 :
								$("#goodsAttr").append('<span style="display:none;">' + text[i].btaName + '</span>' 
										+ " " + '<input id="rg-'
										+ i + '" type="radio" name="rg-'
										+ bgaTattri + '" value="'
										+ text[i].bgaPrice
										+ '"/><label for="rg-' + i + '">'
										+ text[i].bgaValue + '[+'
										+ text[i].bgaPrice.toFixed(2) + ']</label>');
								break;
							case 2 :
								$("#goodsAttr").append('<span style="display:none;">' + text[i].btaName + '</span>'
										+ " " + '<input id="cb-'
										+ i + '" type="checkbox" name="cb-'
										+ bgaTattri + '" value="'
										+ text[i].bgaPrice
										+ '" /><label for="cb-' + i + '">'
										+ text[i].bgaValue + '[+'
										+ text[i].bgaPrice.toFixed(2) + ']</label>');
								break;
							default :
								break;
						}
					} else {
						// 新增属性，重新为bgaTattri赋值
						switch (text[i].btaAtype) {
							case 0 :
								$("#goodsAttr").append("<br/>"
										+ text[i].btaName + ": "
										+ text[i].bgaValue);
								break;
							case 1 :
								$("#goodsAttr").append('<br/>'
										+ '<span>' + text[i].btaName + '</span>' + ': <input id="rg-'
										+ i + '" type="radio" name="rg-'
										+ text[i].bgaTattri + '" value="'
										+ text[i].bgaPrice
										+ '" checked="checked"/><label for="rg-' + i + '">'
										+ text[i].bgaValue + '[+'
										+ text[i].bgaPrice.toFixed(2) + ']</label>');
								break;
							case 2 :
								$("#goodsAttr").append('<br/>'
										+ '<span>' + text[i].btaName + '</span>' + ': <input id="cb-'
										+ i + '" type="checkbox" name="cb-'
										+ text[i].bgaTattri + '" value="'
										+ text[i].bgaPrice
										+ '" /><label for="cb-' + i + '">'
										+ text[i].bgaValue + '[+'
										+ text[i].bgaPrice.toFixed(2) + ']</label>');
								break;
							default :
								break;
						}
						bgaTattri = text[i].bgaTattri;
					}
				}
			}
		},
		error : function(jqXHR, textStatus, errorThrown) {
			MiniuiTools.miniError("系统提示", jqXHR.responseText);
		}
	});
}

/**
 * 选择商品加载对应信息
 */
OrderGoodsHandler.showGoodsInfo = function() {
	var id = mini.get("goodsName").getValue();
	OrderGoodsHandler.getGoodsInfoById(id);
}

/**
 * 加入订单
 */
OrderGoodsHandler.addToOrder = function() {
	// 获取表数据
	// 订单ID
	var bogOid = __boiId;
	// 商品ID
	var bogGid = $("#bgiName label").attr("id");
	
	if(bogGid == null || bogGid == ""){
		MiniuiTools.miniWarning("系统提示", "请选择要添加的商品！");
		return;
	}
	
	// 商品名称
	var bogName = $("#bgiName label").text();
	// 市场售价
	var bogMarket = $("#bgiMarket input").val();
	// 商品售价（选中的价格）
	var bogPrice = 0;
	var select = $("input:checked[name=rgPrice]").attr("id");
	
	if (select == "rgShop" || select == "rgMarket") {
		bogPrice = parseFloat($("input:checked[name=rgPrice]").val());
	} else if (select == "rgCustom") {
		if (!mini.get("custom").validate())
			return;
		bogPrice = parseFloat(mini.get("custom").getValue());
	}
	
	// 商品属性，属性价格
	var bogAttribute = "";
	var bogAttprice = 0;
	var attr = $("#goodsAttr input:checked");
	
	attr.each(function() {
		bogAttprice += parseFloat($(this).val());
		bogAttribute += $(this).prev("span").text() + ":" + $(this).next("label").text() + "<br/>";
	});
			
	if (bogAttribute != "") {
		bogAttribute = bogAttribute.substring(0, bogAttribute.length - 1);
	}
	
	// 购买数量
	var bogNumber = mini.get("goodsNum").getValue();
	// 商品总价=选中的价格+属性总价
	var bogTotal = 0;
	bogTotal = parseFloat((bogPrice + bogAttprice) * bogNumber).toFixed(2);
	// 货号（只用于grid显示）
	var bgiGsn = $("#bgiGsn label").text();
	
	var orderData = {
		bgiGsn : bgiGsn,
		bogOid : bogOid,
		bogGid : bogGid,
		bogName : bogName,
		bogMarket : bogMarket,
		bogPrice : bogPrice,
		bogAttribute : bogAttribute,
		bogAttprice : bogAttprice,
		bogNumber : bogNumber,
		bogTotal : bogTotal
	};
	
	OrderGoodsHandler.orderGoodsGrid.addRow(orderData);
}

// 保存列表中所有商品订单信息
OrderGoodsHandler.saveOrderGoods = function() {
	var orderData = OrderGoodsHandler.orderGoodsGrid.getChanges();
	var gridData = OrderGoodsHandler.orderGoodsGrid.getData();
	var boiGpay = parseFloat(0);

	for (var i = 0, j = gridData.length; i < j; i++) {
		boiGpay += parseFloat(gridData[i].bogTotal);
	}

	boiGpay = boiGpay.toFixed(2);
	
	if (orderData.length > 0) {
		orderData = mini.encode(orderData);
		OrderGoodsHandler.orderGoodsGrid.loading();
		$.ajax({
					url : __root + "/saveOrderGoods.do",
					type : "POST",
					cache : false,
					data : {
						orderData : orderData,
						boiGpay : boiGpay,
						boiId : __boiId,
						operateUType : gbOperateUType,
						operateUser : gbOperateUser,
						operateIp : gbOperateIp
					},
					success : function(text) {
						OrderGoodsHandler.returnOrderDetail();
					},
					error : function(jqXHR, textStatus, errorThrown) {
						MiniuiTools.miniError("系统提示", jqXHR.responseText);
					}
				});
	} else {
		return;
	}
}